import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:re_editor/re_editor.dart';
import 'package:sites_hub/task.dart';

class NotePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _SubPage();
  }
}

class _SubPage extends State<NotePage> {
  final Widget _content = const Center(
    child: Text('空空如也'),
  );
  late TextEditingController _newTaskController;

  @override
  void initState() {
    _newTaskController = TextEditingController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        SizedBox(
          width: 300,
          child: DefaultTabController(
            initialIndex: 0,
            length: 3,
            child: Scaffold(
              appBar: AppBar(
                toolbarHeight: 0,
                leadingWidth: 0,
                titleSpacing: 0,
                notificationPredicate: (ScrollNotification n) {
                  return n.depth == 1;
                },
                scrolledUnderElevation: 4.0,
                shadowColor: Colors.redAccent,
                bottom: const TabBar(tabs: [
                  Tab(
                    icon: Icon(Icons.cloud_outlined),
                    text: 'cloud',
                  ),
                  Tab(
                    icon: Icon(Icons.beach_access_sharp),
                    text: 'beach',
                  ),
                  Tab(
                    icon: Icon(Icons.brightness_5_sharp),
                    text: 'bright',
                  )
                ]),
              ),
              body: TabBarView(children: [
                Builder(builder: (c) {
                  return SizedBox(
                    width: 200,
                    child: Column(
                      children: [
                        TaskList(
                          status: TaskStatus.New,
                        ),
                        TextField(
                          controller: _newTaskController,
                          onSubmitted: (s) {
                            var titleList =
                                context.read<TaskListProvider>().newTaskList;
                            titleList.add(
                                Task(taskContent: s, status: TaskStatus.New));
                            _newTaskController.clear();
                          },
                          decoration: const InputDecoration(
                              prefixIcon: Icon(Icons.add),
                              labelText: '记录备忘',
                              labelStyle:
                                  TextStyle(fontFamily: 'zh', fontSize: 20)),
                        )
                      ],
                    ),
                  );
                }),
                Builder(builder: (c) {
                  return SizedBox(
                    width: 200,
                    child: Column(
                      children: [
                        TaskList(),
                      ],
                    ),
                  );
                }),
                Builder(builder: (c) {
                  return SizedBox(
                    width: 200,
                    child: Column(
                      children: [
                        TaskList(
                          status: TaskStatus.Del,
                        ),
                      ],
                    ),
                  );
                })
              ]),
            ),
          ),
        ),
        Expanded(
            child: Container(
          color: Colors.white,
          child: context.watch<TaskListProvider>().newTaskList.length == 0
              ? _content
              : EditorPage(content: () {
                  var index =
                      context.watch<TaskListProvider>().currentSelectedIndex;
                  var task =
                      context.watch<TaskListProvider>().newTaskList[index];
                  return task.taskContent;
                }()),
        ))
      ],
    );
  }
}

class EditorPage extends StatefulWidget {
  String content;

  EditorPage({super.key, required this.content});

  @override
  State<StatefulWidget> createState() {
    return _EditorPage();
  }
}

class _EditorPage extends State<EditorPage> {
  var c = CodeLineEditingController();

  @override
  void didUpdateWidget(EditorPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    print(999);
    var index = context.watch<TaskListProvider>().currentSelectedIndex;
    var task = context.watch<TaskListProvider>().newTaskList[index];
    var i = task.taskContent == oldWidget.content;
    if (i) {
      return;
    }
    c.text = task.taskContent;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Flexible(
          child: CodeEditor(
            onChanged: (v) {
              var t = c.text;
              print(t);
              var index = context.read<TaskListProvider>().currentSelectedIndex;
              var task = context.read<TaskListProvider>().newTaskList[index];
              task.taskContent = t;
              c.moveCursorToLineEnd();
              context.read<ContentProvider>().update(t);
            },
            controller: c,
            style: CodeEditorStyle(
              backgroundColor: Colors.pinkAccent.withOpacity(0.3),
              cursorLineColor: Colors.blueAccent,
            ),
            indicatorBuilder:
                (context, editingController, chunkController, notifier) {
              return Row(
                children: [
                  DefaultCodeLineNumber(
                    controller: editingController,
                    notifier: notifier,
                  ),
                  DefaultCodeChunkIndicator(
                      width: 20,
                      controller: chunkController,
                      notifier: notifier)
                ],
              );
            },
            wordWrap: true,
          ),
        ),
        SizedBox(
          height: 50,
          child: Row(
            children: [
              MouseRegion(
                onEnter: (_) {},
                onExit: (_) {},
                child: Row(
                  children: [
                    Checkbox(value: () {
                      var index =
                          context.read<TaskListProvider>().currentSelectedIndex;
                      var task =
                          context.read<TaskListProvider>().newTaskList[index];
                      return task.notify;
                    }(), onChanged: (v) {
                      context
                          .read<EditorStateProvider>()
                          .updateRemindMeSelected(v ?? false);
                      var index =
                          context.read<TaskListProvider>().currentSelectedIndex;
                      var task =
                          context.read<TaskListProvider>().newTaskList[index];
                      task.notify = v ?? false;
                    }),
                    const Text('提醒我')
                  ],
                ),
              )
            ],
          ),
        )
      ],
    );
  }

  @override
  void initState() {
    super.initState();
  }
}

class ContentProvider with ChangeNotifier {
  String _content = '';

  String get content => _content;

  void update(String newContent) {
    _content = newContent;
    // notifyListeners();
  }
}

class EditorStateProvider with ChangeNotifier {
  bool _remindMeSelected = false;

  bool get remindMeSelected => _remindMeSelected;

  void updateRemindMeSelected(bool newStatus) {
    _remindMeSelected = newStatus;
    notifyListeners();
  }
}
